<template>
    <div class="home" :style="bgStyle">
        <van-row style="width: 100%; height: 400px;"></van-row>
        <!-- <img src="../../../assets/images/mainbg.jpg" width="100%" height="750px"/> -->
        <div
            style="width: 100%; min-height: 800px; height: 100%; margin-bottom: 20px;background-color: white;text-align: center;">
            <div style="width: 90%;margin: 0 5%;border: 1px solid #C4C4C4;font-size: 20px;border-radius: 14px;position: relative;top: -15px;background-color: white;padding: 30px 0;">
                <div style="padding: 0 20px;color: white;">
                    <van-row justify="space-around">
                    <van-col span="8">
                        <div style="padding-top: 10px;border-radius: 14px;border: 5px solid #0aafc3;background: linear-gradient(90deg, #3cc0d0, #51d8ec);" @click="startAnwer">
                            <van-icon name="todo-list-o" size="40" />
                            <div style="padding: 10px 0;">闯关答题</div>
                        </div>
                    </van-col>
                    <van-col span="8">
                        <div style="padding-top: 10px;border-radius: 14px;border: 5px solid #fd4175;background: linear-gradient(90deg, #fd608c, #fb799e);" @click="startPractise">
                            <van-icon name="records-o" size="40" />
                            <div style="padding: 10px 0;">模拟练习</div>
                        </div>
                    </van-col>
                </van-row>
                <van-row justify="space-around"  style="margin-top: 25px;">
                    <van-col span="8">
                        <div style="padding-top: 10px;border-radius: 14px;border: 5px solid #E17D00;background: linear-gradient(90deg, #E8972B, #E8AF29);" @click="goLearn">
                            <van-icon name="desktop-o" size="40" />
                            <div style="padding: 10px 0;">学习园地</div>
                        </div>
                    </van-col>
                    <van-col span="8">
                        <div style="padding-top: 10px;border-radius: 14px;border: 5px solid #6fc53f;background: linear-gradient(90deg, #87cf5f, #99da6f);" @click="goMemo">
                            <van-icon name="question-o" size="40" />
                            <div style="padding: 10px 0;">活动说明</div>
                        </div>
                    </van-col>
                </van-row>
                </div>
            </div>
        </div>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getTask, getAppSetting, getQuestion } from '@/api/task.js';
import { getInfo,getJssdkConfig } from '@/api/base.js';
import { wxLogin } from '@/api/user';
import { showNotify,showFailToast } from 'vant'
import wx from "weixin-js-sdk";
const emit = defineEmits(['modifyActive'])

const route = useRoute();
const router = useRouter();

let taskId = route.params.id;
console.log(route.params)
if(taskId){
    localStorage.setItem('taskId', taskId)
}else{
    taskId = localStorage.getItem('taskId')
    console.log("没有取得ID",taskId)
}

const nowAppSetting = ref({});
const initAppSetting = ref({
    "home": {
        "bgStyle": {
            "backgroundColor": "#fff",
            "backgroundRepeat": "no-repeat",
            "backgroundSize": "contain"
        }
    },
    "activeProcess": {},
    "answerAnalysis": {},
    "successfulChallenge": {},
    "shareEffect": {}
});

const taskInfo = ref({
  startTime: "",
  endTime: "",
  awards: [],
  organizer: "",
  memo: "",
  awardsPoints: '',  
})

const bgStyle = computed(() => {
    let tempBgStyle = initAppSetting.value.home.bgStyle;
    if(nowAppSetting){
        if (nowAppSetting.value.home && nowAppSetting.value.home.bgStyle) {
        tempBgStyle = { ...tempBgStyle, ...nowAppSetting.value.home.bgStyle }
    }
    }
    return tempBgStyle;
})

onMounted(() => {
    emit("modifyActive","")
    login();
    getAppSettings();
    getTaskInfo();
})

function getAppSettings() {
    getAppSetting({ taskId }).then(res => {
        console.log(res, 'res - getAppSetting');
        if (res.code == 200) {
            nowAppSetting.value = res.data;
        }
    })
}

// 获取任务信息
function getTaskInfo() {
    getTask(taskId).then(res => {
        console.log(res)
        taskInfo.value = res.data;
    })
}

function login() {
    if (sessionStorage.getItem('noToken') == 'noToken') {
        return false;
    }
    // 确保每次都刷新 token 
    const token = sessionStorage.getItem('token');
    if (!token) {
        const code = route.query.code;
        if (code) {
            console.log(1);
            wxLogin(code).then((res) => {
                console.log(res, 'res');

                sessionStorage.setItem('token', res.openid)
                localStorage.setItem('token', res.openid)
                localStorage.setItem('avatar', res.headimgurl)
                localStorage.setItem('niceName', res.nickname)

                const fullPath = localStorage.getItem('fullPath');
                console.log(fullPath, 'fullPath');

                getWxConfig()

                // if (fullPath) {
                //   location.href = fullPath
                // } else {
                //   location.href = '/'
                // }
            })
        } else {
            console.log('重定向授权');

            const appid = process.env.VUE_APP_WX_APPID;
            const redirect_uri = location.href;
            const redirect_url = encodeURIComponent(redirect_uri);
            const scope = "snsapi_userinfo"; // snsapi_userinfo || snsapi_base
            let state = ''
            state = encodeURIComponent(state);
            var url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirect_url}&response_type=code&scope=${scope}&state=${state}#wechat_redirect`
            window.location.href = url
        }
    }
}

function getWxConfig() {
    // 获取微信配置
    const url = location.href.split('#')[0];
    console.log('url', url);
    getJssdkConfig(url).then(res => {
        console.log('getwxconfig', res)
        wx.config({
            debug: false,
            appId: res.data.appId,
            timestamp: res.data.timestamp,
            nonceStr: res.data.nonceStr,
            signature: res.data.signature,
            jsApiList: ['getLocation', 'updateAppMessageShareData'] // 必填，需要使用的JS接口列表
        });
        wx.error(function (res) {
            console.log('error', res)
            // const tryGetConfig = sessionStorage.getItem("tryGetConfig")
            // if(tryGetConfig != true){
            //     sessionStorage.setItem("tryGetConfig",true)
            //     sessionStorage.removeItem('token');
            //     login()
            // }
            
        })
        wx.ready(() => {
            console.log('ready', wx)
            // 获取地理位置
            wx.getLocation({
                type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                success: function (res) {
                    console.log('getLocation', res)
                    const latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                    const longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                    const speed = res.speed; // 速度，以米/每秒计
                    const accuracy = res.accuracy; // 位置精度
                    localStorage.setItem('latitude', latitude)
                    localStorage.setItem('longitude', longitude)
                }
            })

            getAppSetting({ taskId }).then(res => {
                if (res.code == 200) {
                    console.log(res.data, 'getAppSetting res.data');
                    if (res.data.shareEffect && res.data.shareEffect.share) {
                        const shareObj = res.data.shareEffect.share;
                        wx.updateAppMessageShareData({
                            title: shareObj.title, // 分享标题
                            desc: shareObj.content, // 分享描述
                            link: url, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                            imgUrl: shareObj.icon, // 分享图标
                            success: function () {
                                // 设置成功
                            }
                        })
                    }
                }
            })
        })
    })
}

function startAnwer() {
  const data = {
    taskId
  };
  data.latitude = localStorage.getItem('latitude');
  data.longitude = localStorage.getItem('longitude');
  data.memberId = localStorage.getItem('token');
  data.preview = true;
  getQuestion(data).then(res=>{
    console.log(res, 'res');
    if (res.code == 200) {
      router.push(`/answer/${taskId}`)
    } else {
      showNotify({ message: res.msg, type: 'danger' })
    }
  })
}

function startPractise(){
    const data = {
    taskId
  };
  data.latitude = localStorage.getItem('latitude');
  data.longitude = localStorage.getItem('longitude');
  data.memberId = localStorage.getItem('token');
  data.preview = true;
  getQuestion(data).then(res=>{
    console.log(res, 'res');
    if (res.code == 200) {
      router.push(`/answer/${taskId}/preactise`)
    } else {
      showNotify({ message: res.msg, type: 'danger' })
    }
  })
}

function goLearn(){
    emit("modifyActive","learn")
    router.replace(`/learn`)
}

function goMemo(){
    router.push(`/home/memo`)
}

</script>
<style lang="less" scoped>
.home {
    width: 100%;
    height: auto;
    min-height: 750px;
    background: url(../../../assets/images/mainbg.jpg) no-repeat;
    overflow-y: auto;

    /deep/ .van-row .van-button {
        margin: 10rem auto;
        width: 200px;
        height: 50px;
        line-height: 50px;
        text-align: center;
        border-radius: 25px;
        background: #2b3fc5;
        color: #fff;
    }
}</style>